<template>
    <div class="login-container">
        <!-- 导航栏 -->
        <van-nav-bar title="登录" class="page-nav-bar" @click-left="handleClickLeft">
            <template #left>
                <van-icon name="arrow-left" />
            </template>
        </van-nav-bar>
        <!-- 导航栏 -->

        <!-- 登录表单 -->
        <van-form
            @submit="handleLoginFormSubmit"
            submit-on-enter
            :show-error="false"
            ref="loginFormRef"
            validate-trigger="onSubmit"
        >
            <van-field
                v-model="user.mobile"
                name="mobile"
                label="手机号"
                type="digit"
                placeholder="请输入手机号"
                :rules="formRules.mobile"
                autofocus
                clearable
                :maxlength="11"
            >
                <template #left-icon>
                    <i class="toutiao toutiao-shouji" />
                </template>
            </van-field>
            <van-field
                v-model="user.validateCode"
                name="code"
                label="验证码"
                type="digit"
                placeholder="请输入验证码"
                :rules="formRules.code"
                autocomplete="off"
                :maxlength="6"
            >
                <template #left-icon>
                    <i class="toutiao toutiao-yanzhengma" />
                </template>
                <template #button>
                    <van-button
                        round
                        size="small"
                        class="van-button__yanzhengma"
                        native-type="button"
                        :disabled="codeBtnDisabled"
                        @click="handleCodeSend"
                    >
                        <van-count-down
                            :time="1000 * time"
                            :auto-start="false"
                            ref="countDownRef"
                            @finish="codeBtnDisabled = !codeBtnDisabled"
                        >
                            <template #default="timeData">
                                获取验证码
                                <span v-show="codeBtnDisabled">
                                    ({{ timeData.seconds }}s)
                                </span>
                            </template>
                        </van-count-down>
                    </van-button>
                </template>
            </van-field>
            <div style="margin: 16px;">
                <van-button
                    block
                    type="info"
                    native-type="submit"
                    class="submit-button"
                >
                    登录
                </van-button>
            </div>
        </van-form>
        <!-- 登录表单 -->
    </div>
</template>

<script>
import { loginReq, sendSms } from '@/api/user';

export default {
    name: 'Login',
    data () {
        const mobileReg = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
        const codeReg = /^\d{6}$/;
        return {
            user: {
                mobile: '', // 手机号
                validateCode: '246810' // 验证码
            },
            codeBtnDisabled: false,
            time: 60, // 验证码短信发送倒计时
            formRules: {
                mobile: [
                    { required: true, message: '请输入手机号' },
                    { pattern: mobileReg, message: '请输入正确的手机号' }
                ],
                code: [
                    { required: true, message: '请输入验证码' },
                    { pattern: codeReg, message: '请输入正确的验证码' }
                ]
            }
        };
    },
    methods: {
        handleLoginFormSubmit (loginForm) {
            // 发送请求
            this.$toast.loading({
                message: '登录中',
                duration: 0,
                forbidClick: true
            });
            loginReq(loginForm)
                .then(res => {
                    this.$toast.success('登录成功');
                    this.$store.commit('saveToken', res.data.data);
                    this.$router.push({
                        name: 'layout'
                    });
                })
                .catch(err => {
                    if (String(err).indexOf('code 400') !== -1) { this.$toast.fail('手机号或验证码错误'); } else {
                        console.log(err);
                        this.$toast.fail('发生未知错误');
                    }
                });
        },
        handleCodeSend () {
            this.$refs.loginFormRef
                .validate('mobile')
                .then(() =>
                    // 校验成功 发送验证码
                    sendSms(this.user.mobile)
                )
                .then(() => {
                    this.$toast.success('发送短信成功');
                    // 验证码发送成功，开启倒计时
                    this.codeBtnDisabled = true;
                    this.$refs.countDownRef.reset();
                    this.$refs.countDownRef.start();
                })
                .catch(err => {
                    // 捕获失败请求
                    if (err.response.status === 429) { this.$toast.fail('请不要频繁获取短信验证码'); } else this.$toast.fail(err.message);
                });
        },
        handleClickLeft () {
            this.$router.back();
        }
    }
};
</script>
<style lang="less" scoped>
.van-button__yanzhengma {
    height: 50px;
    border: 1px solid #666;
    background-color: transparent;
    .van-button__text {
        font-size: 22px;
        color: #666;
    }
}

.van-field {
    display: flex;
    align-items: flex-start;
    padding-top: 50px;
}

.submit-button {
    background-color: #3296fa;
}
</style>
